<?php
/**
* @version 1.0.0
* @package RSSearch! 1.0.0
* @copyright (C) 2011 www.rsjoomla.com
* @license GPL, http://www.gnu.org/licenses/gpl-2.0.html
*/
defined( '_JEXEC' ) or die( 'Restricted access' );
 

jimport('joomla.plugin.plugin');

class plgRSSearchK2 extends JPlugin
{
	function plgRSSearchK2( &$subject )
	{
	    parent::__construct( $subject );
		jimport('joomla.html.parameter');
	    $this->_plugin = JPluginHelper::getPlugin('rssearch', 'k2');
	    $this->_params = new JParameter($this->_plugin->params);
	}
	function getResults(&$results, $search, $params)
	{
	    $app = &JFactory::getApplication();
	    $db =& JFactory::getDBO();

	    $fields = (array)$this->_params->get('searchfields','');
	    $categories = (array) $this->_params->get('categories','');
	    $orderby = $this -> _params->get('orderby','title');
	    $asc_desc = $this -> _params->get('asc_desc','ASC');
	    $itemId = $params->get('itemid','');
	    $itemId = (empty($itemId) ? '' : '&Itemid='.$itemId);

		foreach($fields as $field){
			if($field == 'k2_items'){
				
				$tablecolumns = array('title','hits','ordering','created');
				
				$where_catid = '';
				if(!in_array('', $categories)){
					JArrayHelper::toInteger($categories);
					$where_catid = " AND `#__k2_items`.`catid` IN (".implode(',', $categories).")";
				}
				$query = "SELECT #__k2_items.id, #__k2_items.title, #__k2_items.alias, #__k2_items.catid, #__k2_items.introtext FROM #__k2_items
				WHERE (#__k2_items.title LIKE '%".$search."%' OR #__k2_items.introtext LIKE '%".$search."%' OR #__k2_items.fulltext LIKE '%".$search."%') AND #__k2_items.published = '1' ".$where_catid."
				GROUP BY #__k2_items.id ORDER BY ".(in_array($orderby,$tablecolumns) ? '#__k2_items.'.$orderby : '')." ".$asc_desc."";


				$db -> setQuery($query);
				$list = $db->loadObjectList();
				foreach ($list as $item)
				{
					$tmp = new stdClass();
					$tmp->title = $item -> title;
					$tmp->link = JRoute::_('index.php?option=com_k2&view=item&id='.$item->id.':'.$item->alias.''.$itemId);
					$tmp->text = $item ->introtext;
					$results[] = $tmp;
				}
			}elseif($field == 'k2_categories'){

				JArrayHelper::toInteger($categories);
				$where_id = " AND `#__k2_categories`.`id` IN (".implode(',', $categories).")";

				$query = "SELECT `id`,`name`, `alias`,`description` FROM #__k2_categories 
				WHERE (`name` LIKE '%".$search."%' OR `description` LIKE '%".$search."%') AND `published` = '1' ".$where_id."
				GROUP BY `id`,`name`, `description` ORDER BY ".($orderby == 'ordering' ? $orderby : "ordering")." ".$asc_desc."";

				$db -> setQuery($query);
				$list = $db->loadObjectList();
				foreach ($list as $item)
				{
					$tmp = new stdClass();
					$tmp->title = $item->name;
					$tmp->link = JRoute::_('index.php?option=com_k2&view=itemlist&task=category&id='.$item->id.':'.$item->alias.$itemId);
					$tmp->text = $item->description;
					$results[] = $tmp;
				}
			}
		}
	    return true;
	}
}

?>